package com.bw.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bw.bean.CArticle;
import com.bw.bean.CCategory;
import com.bw.bean.CChannel;
import com.bw.service.ServiceL;
import com.github.pagehelper.PageInfo;

@Controller
public class ArticleController {
	@Autowired
	private ServiceL service;
	
	@RequestMapping("list")
	public String listArt(Model model,String name,String cid,@RequestParam(defaultValue = "1")int pageNum) {
		System.out.println(name);
		int pageSize=3;
		PageInfo<CArticle> page=service.listArt(pageNum,pageSize,name,cid);
		model.addAttribute("pg", page);
		model.addAttribute("name", name);
		model.addAttribute("cid", cid);
		return "list";
	}
	
	@RequestMapping("selectchannel")
	@ResponseBody
	public List<CChannel> selectchannel() {
		List<CChannel> cha=service.selectchannel();
		return cha;
	}
	
	@RequestMapping("tianatr")
	public String tianatr() {
		return "add";
	}
	
	@RequestMapping("addarticle")
	public String addarticle(CArticle art,MultipartFile myFile,HttpServletRequest request) throws IllegalStateException, IOException {
		if(myFile!=null && myFile.getSize()>1) {
			String real = request.getServletContext().getRealPath("/img/");
			String ori = myFile.getOriginalFilename();
			ori=UUID.randomUUID().toString()+ori;
			File file = new File(real,ori);
			myFile.transferTo(file);
			art.setPicture(ori);
		}
		
		boolean aa=service.addarticle(art);
		System.out.println(aa);
		return "redirect:/list";
	}
	
	@RequestMapping("selectcategory")
	@ResponseBody
	public List<CCategory> selectcategory() {
		List<CCategory> list=service.selectcategory();
		return list;
		
	}
}
